package com.huazai.yangge.completable.future;

import java.util.concurrent.*;

/**
 * @author 华仔
 * @date 2024/2/21
 */
public class CompletableFutureWithThreadPoolDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 注意：
        final ExecutorService executorService = Executors.newFixedThreadPool(5);
        try {
            final CompletableFuture<Void> completableFuture = CompletableFuture.supplyAsync(() -> {
                        try {
                            TimeUnit.MILLISECONDS.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("000 = " + Thread.currentThread().getName());
                        return "abc";
                    }, executorService).thenRunAsync(() -> {
                        try {
                            TimeUnit.MILLISECONDS.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("111 = " + Thread.currentThread().getName());
                    }).thenRun(() -> {
                        try {
                            TimeUnit.MILLISECONDS.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("2222 = " + Thread.currentThread().getName());
                    })
                    .thenRun(() -> {
                        try {
                            TimeUnit.MILLISECONDS.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("3333 = " + Thread.currentThread().getName());
                    });

            System.out.println("completableFuture = " + completableFuture.get());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            executorService.shutdown();
        }
    }
}

// thenRun 任务A执行完执行任务B， 并且B不需要A的结果
// thenAccept 任务A执行完执行任务B， B需要A的结果， 但是B无返回值
// thenApply 任务A执行完执行任务B， B需要A的结果 同时任务B有返回值






